package com.mangosteen.interviewji.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mangosteen.interviewji.common.ErrorCode;
import com.mangosteen.interviewji.exception.BusinessException;
import com.mangosteen.interviewji.manager.AiManager;
import com.mangosteen.interviewji.mapper.QuestionMapper;
import com.mangosteen.interviewji.model.entity.Question;
import com.mangosteen.interviewji.model.entity.User;
import com.mangosteen.interviewji.model.entity.UserQuestion;
import com.mangosteen.interviewji.mapper.UserQuestionMapper;
import com.mangosteen.interviewji.model.vo.QuestionVO;
import com.mangosteen.interviewji.service.QuestionService;
import com.mangosteen.interviewji.service.UserQuestionService;
import com.mangosteen.interviewji.service.UserService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.UnitsTools;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author ASUS
* @description 针对表【user_question(用户答题记录)】的数据库操作Service实现
* @createDate 2025-11-07 17:06:41
*/
@Service
@Slf4j
public class UserQuestionServiceImpl extends ServiceImpl<UserQuestionMapper, UserQuestion>
    implements UserQuestionService{


    @Resource
    private AiManager aiManager;

    @Resource
    private QuestionService questionService;


    @Resource
    UserQuestionMapper userQuestionMapper;

    @Resource
    @Lazy
    private UserService userService;
    @Override
    @Transactional
    public UserQuestion submit(String userAnswer, Long questionId, User loginUser) {
        if (ObjectUtil.hasEmpty(userAnswer,questionId,loginUser)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"参数错误");
        }
        QueryWrapper<UserQuestion> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",loginUser.getId());
        queryWrapper.eq("question_id",questionId);
        UserQuestion userQuestion = this.getOne(queryWrapper);

        QueryWrapper<Question> questionQueryWrapper = new QueryWrapper<>();
        questionQueryWrapper.eq("id",questionId);
        Question question = questionService.getOne(questionQueryWrapper);
        String questionAnswer=question.getAnswer();

        UserQuestion userQuestionAI = aiGenerateAccuracy(userAnswer,questionAnswer);
        if (userQuestion== null){
            userQuestion = new UserQuestion();
            userQuestion.setUser_id(loginUser.getId());
            userQuestion.setQuestion_id(questionId);
            userQuestion.setUser_answer(userAnswer);
            userQuestion.setAccuracy(userQuestionAI.getAccuracy());
            userQuestion.setAnalysis(userQuestionAI.getAnalysis());
            userQuestion.setSubmit_count(1);
            userQuestionMapper.insert(userQuestion);
        }else {
            userQuestion.setSubmit_count(userQuestion.getSubmit_count()+1);
            userQuestion.setUser_answer(userAnswer);
            userQuestion.setAccuracy(userQuestionAI.getAccuracy());
            userQuestion.setAnalysis(userQuestionAI.getAnalysis());
            userQuestionMapper.updateById(userQuestion);
        }
        //每提交一次都进行添加
        userService.addUserDailyAnswer(loginUser.getId());

        return userQuestion;
    }

    @Override
    public Page<QuestionVO> getUserRecordHistory(Long current, Long size, Long id,HttpServletRequest  request) {
        QueryWrapper<UserQuestion> userQuestionQueryWrapper = new QueryWrapper<>();
        userQuestionQueryWrapper.eq("userId",id);
        List<UserQuestion> questionList = this.list(userQuestionQueryWrapper);
        List<Long> questionIdList = questionList.stream().map(UserQuestion::getQuestion_id).collect(Collectors.toList());

        return questionService.getQuestionVOPage(current,size,questionIdList,request);
    }


    private UserQuestion aiGenerateAccuracy(String userAnswer,String questionAnswer) {
        String systemPrompt = "你现在是一个专业的面试评分系统，根据用户输入的答案和系统答案对用户答案进行打分并输出并给出优化建议" +
                "要求如下：" +
                "1.输出俩个字段accuracy是一个1-100的整数作为百分比分数，analysis是分析的优化建议，字数在20-100" +
                "2.用户输入答案完全不正确就给0分，可以严格一点" +
                "3.结合系统答案给出优化建议，主要贴合面试场景的回答" +
                "+\n" +
                "\"除此之外，请不要输出任何多余的内容，不要输出开头、也不要输出结尾，只输出上面的俩个字段，并且不要用markdown形式包裹。" +
                " +\n" +
                " \"接下来我会给你用户输入的答案和系统答案";
        String userPrompt = "请结合用户答案"+userAnswer+"和系统答案"+questionAnswer+"进行打分并给出优化建议";
        String result = aiManager.doChat(systemPrompt, userPrompt);
        System.out.println("result: " + result);
        // 使用JSON解析替代字符串分割
            try {
                ObjectMapper mapper = new ObjectMapper();
                JsonNode root = mapper.readTree(result);

                // 解析字段
                String accuracy = root.get("accuracy").asText();
                String analysis = root.get("analysis").asText();

                System.out.println("Accuracy: " + accuracy);
                System.out.println("Analysis: " + analysis);
                UserQuestion userQuestion = new UserQuestion();
                userQuestion.setAccuracy(String.valueOf(accuracy));
                userQuestion.setAnalysis(analysis);
                return userQuestion;
            } catch (Exception e) {
                e.printStackTrace();
            }
           return null;
    }
}




